package com.biubiushop.Socket.NIOChatRoom;

import cn.hutool.core.util.RandomUtil;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * @author chenjia
 * @date 2019/7/19
 **/
public class SocketChannelClient {

    public void start() throws IOException {
        //连接服务端
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9999));

        //接受服务器端响应
        //新开线程,负责接受服务端的响应数据
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ, RandomUtil.randomString(8));
        new Thread(new NioClientHandler(selector)).start();

        //向服务器发送数据
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String request = scanner.nextLine();
            if(request!=null && request.length()>0){
                socketChannel.write(Charset.forName("UTF-8").encode(request));
            }
        }

    }

    public static void main(String[] args) throws Exception {
        new SocketChannelClient().start();
    }
}
